/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from 'react';
import { Form, Button, Input, message, Typography, Space } from 'antd';
import { getSmsSensitiveWord } from '@/services/customerSearch';
const FormItem = Form.Item;
const { TextArea } = Input;
const { Text } = Typography;

interface FormValuesType {
  content: string;
}

interface SensitiveWordType {
  text: string;
  danger: boolean;
  id: string;
}

const SmsSensitiveWord = () => {
  const [content, setContent] = useState<SensitiveWordType[]>([]);
  const [formValue, setFormValue] = useState<FormValuesType>();
  const [form] = Form.useForm();

  const onFinish = async (values: FormValuesType) => {
    const { code, msg, data } = await getSmsSensitiveWord(values);
    if (code == 0) {
      if (data.word) {
        const reg = new RegExp(data.word, 'gi');
        const newcontent = values.content.replace(reg, ` ${data.word} `).split(' ');
        setContent(
          newcontent.map((item, index) => ({
            text: item,
            danger: item === data.word,
            id: index.toString(),
          })),
        );
      } else {
        setContent([]);
        message.success(msg);
      }
    } else {
      setContent([]);
      message.error(msg);
    }
  };
  const onValuesChange = (values: FormValuesType) => {
    // console.info('onValuesChange', values);
    setFormValue(values);
  };

  useEffect(() => {
    setContent([]);
  }, [formValue?.content]);

  const onReset = () => {
    form.resetFields(['content']);
    setContent([]);
  };

  return (
    <>
      <Form
        form={form}
        onFinish={onFinish}
        onValuesChange={onValuesChange}
        style={{ marginBottom: 20 }}
        labelWrap
      >
        <div style={{ marginBottom: 10 }}>短信模版内容</div>
        <FormItem name='content' rules={[{ required: true, message: '请输入短信模版内容' }]}>
          <TextArea
            rows={8}
            style={{ maxWidth: '600px' }}
            placeholder='请输入短信模版内容'
            showCount
            allowClear
          />
        </FormItem>
        <FormItem>
          <Button type='primary' htmlType='submit' loading={false}>
            检测敏感字
          </Button>
          <Button style={{ marginLeft: 10 }} onClick={onReset}>
            重置
          </Button>
        </FormItem>
      </Form>
      {!!content.length && (
        <Space direction='horizontal' wrap style={{ maxWidth: '600px' }}>
          <Text>短信内容:</Text>
          {content.map((item) => (
            <Text key={item.id} {...(item.danger ? { type: 'danger' } : {})}>
              {item.text}
            </Text>
          ))}
        </Space>
      )}
    </>
  );
};

export default SmsSensitiveWord;
